package com.wei.hotword.service;

import cn.hutool.core.date.DateUtil;
import com.wei.hotword.mapper.HotWordMapper;
import com.wei.hotword.pojo.HotWordDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class HotwordService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private HotWordMapper hotWordMapper;

    /**
     * 设置缓存失效时间，统一为凌晨零点
     *
     * @param hotWord
     * @throws Exception
     */
    public void addHotWord(String hotWord) throws Exception {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);


        //晚上十二点与当前时间的毫秒差
        Long timeOut = (calendar.getTimeInMillis() - System.currentTimeMillis()) / 1000;
        // 判断是否同一个人搜索
        Boolean exist = redisTemplate.opsForValue().setIfAbsent("hotword::1::" + hotWord, 1, timeOut, TimeUnit.SECONDS);
        if (!exist) {
            return;
        }
        redisTemplate.expire("hotWord", timeOut, TimeUnit.SECONDS);
        redisTemplate.opsForZSet().incrementScore("hotWord", hotWord, 1); // 加入排序set
    }

    public static void main(String[] args) {
        System.out.println(DateUtil.beginOfDay(DateUtil.date()));
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        //晚上十二点与当前时间的毫秒差
        Long timeOut = (calendar.getTimeInMillis() - System.currentTimeMillis()) / 1000;
        System.out.println(DateUtil.betweenMs(DateUtil.beginOfDay(DateUtil.offsetDay(DateUtil.date(), 1)), DateUtil.date()));
        System.out.println(calendar.getTimeInMillis() - System.currentTimeMillis());
    }

    /**
     * 获取热词前五位
     *
     * @return
     */
    public List<HotWord> getHotWord() {
        List<HotWord> hotWordList = new ArrayList<>();
        Set<ZSetOperations.TypedTuple<Object>> typedTupleSet = redisTemplate.opsForZSet().reverseRangeByScoreWithScores("hotWord", 1, 100);
        Iterator<ZSetOperations.TypedTuple<Object>> iterator = typedTupleSet.iterator();
        int flag = 0;
        while (iterator.hasNext()) {
            flag++;
            ZSetOperations.TypedTuple<Object> typedTuple = iterator.next();
            String value = (String) typedTuple.getValue();
            int score = (int) Math.ceil(typedTuple.getScore());
            HotWord hotWord = new HotWord(score, value);
            hotWordList.add(hotWord);
            if (flag >= 5) break;
        }
        return hotWordList;
    }

    /**
     * 当天数据存储到数据库中
     */
    public void putDb() {
        Long number = redisTemplate.opsForZSet().zCard("hotWord");
        Set<ZSetOperations.TypedTuple<Object>> typedTupleSet = redisTemplate.opsForZSet().reverseRangeWithScores("hotWord", 0, number);
        for (ZSetOperations.TypedTuple<Object> typedTuple : typedTupleSet) {
            String value = (String) typedTuple.getValue();
            int score = (int) Math.ceil(typedTuple.getScore());
            HotWordDO hotWord = new HotWordDO();
            hotWord.setWord(value);
            hotWord.setScore(score);
            hotWord.setDate(new Date());
            hotWordMapper.insert(hotWord);
        }
    }

}
